package com.sunrise.gateway.web.servlet;

import com.dap.exception.ErrorCodeContainer;
import com.dap.utils.QrCodeUtil;
import com.sunrise.gateway.commons.CommonUtils;
import com.sunrise.gateway.commons.Result;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class QrCodeServlet extends ServletBase {
    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void doMyPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        execute(req, resp);
    }
    @Override
    protected void doMyGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        execute(req, resp);
    }

    protected void execute(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String content = req.getParameter("content");
        if (StringUtils.isEmpty(content)) {
            Result result = new Result(com.dap.commons.Constants.ResponseCode.SYS_ERROR, "请输入二维码内容", null);
            CommonUtils.writeStrIntoResponse(result.toJsonString(), resp);
            return;
        }

        String qrCodeSizeStr = req.getParameter("qrCodeSize");
        if (StringUtils.isEmpty(qrCodeSizeStr)) {
            Result result = new Result(com.dap.commons.Constants.ResponseCode.SYS_ERROR, "请输入二维码大小", null);
            CommonUtils.writeStrIntoResponse(result.toJsonString(), resp);
            return;
        }
        int qrCodeSize;
        try {
            qrCodeSize = Integer.parseInt(qrCodeSizeStr);
        } catch (Exception e) {
            Result result = new Result(com.dap.commons.Constants.ResponseCode.SYS_ERROR, "请输入二维码大小", null);
            CommonUtils.writeStrIntoResponse(result.toJsonString(), resp);
            return;
        }

        String imageFormat = req.getParameter("imageFormat");
        if (StringUtils.isEmpty(imageFormat)) {
            Result result = new Result(com.dap.commons.Constants.ResponseCode.SYS_ERROR, "请输入二维码图片格式", null);
            CommonUtils.writeStrIntoResponse(result.toJsonString(), resp);
            return;
        }
        imageFormat = imageFormat.toLowerCase();


        try {
            QrCodeUtil.createQrCode(resp.getOutputStream(), content, qrCodeSize, imageFormat);
        } catch (Exception e) {
            LOGGER.error("", e);

            Result result = new Result(com.dap.commons.Constants.ResponseCode.SYS_ERROR, ErrorCodeContainer.getErrorMessage(com.dap.commons.Constants.ResponseCode.SYS_ERROR), null);
            CommonUtils.writeStrIntoResponse(result.toJsonString(), resp);
        }
    }

}
